<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      title="登录"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- /导航栏 -->

    <!-- 登录表单 -->
    <van-form @submit="onSubmit" ref="loginFormRef">
      <van-field
        name="mobile"
        placeholder="请输入手机号"
        autocomplete="off"
        clearable
        v-model="user.mobile"
        :rules="userRules.mobile"
        type="number"
        maxlength="11"
      >
        <i slot="left-icon" class="iconfont icon-shouji"></i>
      </van-field>

      <van-field
        name="code"
        placeholder="请输入验证码"
        autocomplete="off"
        clearable
        v-model="user.code"
        :rules="userRules.code"
        type="number"
        maxlength="6"
      >
        <i slot="left-icon" class="iconfont icon-yanzhengma"></i>
        <template #button>
          <van-button
            v-if="sendCodeFlag"
            native-type="button"
            round
            class="send-sms-btn"
            size="small"
            type="info"
            @click="sendCode"
            >发送验证码</van-button
          >

          <van-count-down
            round
            ref="countSecound"
            v-else
            :time="5000"
            format="mm:ss"
            @finish="sendCodeFlag = true"
          />
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button
          class="login-btn"
          block
          round
          type="info"
          native-type="submit"
          aria-disabled="true"
        >
          登录
        </van-button>
      </div>
    </van-form>
    <!-- /登录表单 -->
  </div>
</template>

<script>
import { LoginAPI, setCOdeAPI } from '@/api'
export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        mobile: '17090086870',
        code: '246810'
      },
      userRules: {
        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            pattern: /^1[3|5|6|7|8]\d{9}$/,
            message: '手机号格式不正确',
            trigger: 'onChange'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式不正确',
            trigger: 'onChange'
          }
        ]
      },
      sendCodeFlag: true
    }
  },
  methods: {
    async onSubmit (values) {
      try {
        // try 代码块中，响应报文的状态为4XX/5XX会catch,其他会正常执行
        const res = await LoginAPI(values)
        this.$toast.loading({
          message: '登陆中',
          forbidClick: true,
          duration: 1000
        })

        if (res.status === 201) {
          this.$toast.success({
            message: '登录成功',
            forbidClick: true,
            duration: 1000
          })

          this.$store.commit('setUser', res.data.data)
          this.$router.push('/my')
        } else {
          this.$toast.fail({
            message: '登录失败',
            forbidClick: true,
            duration: 1000
          })
        }
      } catch (error) {
        let errMag = '手机号或者验证码错误'
        if (error.response.status !== 400) errMag = '服务器繁忙,请稍后再试'
        this.$toast.fail({
          message: errMag,
          forbidClick: true,
          duration: 1000
        })
      }
    },
    async sendCode () {
      // 1. 验证手机号
      try {
        await this.$refs.loginFormRef.validate('mobile')
        // console.log('验证成功')
      } catch (error) {
        console.log('验证失败' + error)
      }

      // 2. 触发验证码发送
      try {
        const res = await setCOdeAPI(this.user.mobile)
        // console.dir(res)
        if (res.status === 200) {
          this.$toast.success({
            message: '验证码获取成功',
            forbidClick: true,
            duration: 1000
          })
          // 3.倒计时
          this.sendCodeFlag = false
        } else {
          return this.$toast.fail({
            message: '验证码获取失败',
            forbidClick: true,
            duration: 1000
          })
        }
      } catch (error) {
        // console.dir(error)
        let errMsg = '验证码发送异常'
        if (error.response.status === 404) errMsg = '手机号不正确'
        if (error.response.status === 429) {
          errMsg = '发送短信太频繁,请一分钟后再试'
        }
        return this.$toast.fail({
          message: errMsg,
          forbidClick: true,
          duration: 1000
        })
      }
    }
  }
}
</script>
<style scoped lang="less">
.login-container {
  .iconfont {
    font-size: 37px;
  }
  .send-sms-btn {
    width: 156px;
    height: 46px;
    line-height: 46px;
    background-color: #ededed;
    font-size: 12px;
    color: #666;
  }
  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
    }
  }

  .van-count-down {
    display: inline-block;
    color: #666;
    background-color: #ededed;
  }
}
</style>
